/**
 * @ClassName KP21_mergeTwoSortedLinkedList
 * @Description: TODO
 * @Author: JCC
 * @CreateTime: 2023/10/14 20:38
 */

/**
 * 合并两个有序链表
 */
public class KP21_mergeTwoSortedLinkedList {
    static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    /**
     * 合并有序表
     * @param list1
     * @param list2
     * @return
     */
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null || list2 == null) {
            return list1 == null ? list2 : list1;
        }
        ListNode head = list1.val >= list2.val ? list2 : list1;
        ListNode pre = head;
        ListNode l1 = head.next;
        ListNode l2 = head == list1 ? list2 : list1;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                pre.next = l1;
                pre = l1;
                l1 = l1.next;
            } else {
                pre.next = l2;
                pre = l2;
                l2 = l2.next;
            }
        }
        if (l1 != null) {
            pre.next = l1;
        }
        if (l2 != null) {
            pre.next = l2;
        }
        return head;
    }
}
